package com.bw.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;


public class BaseLogApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> dataStreamSource = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer("topic_log", "topic_log_dwd_split"));
//        dataStreamSource.print();
        SingleOutputStreamOperator<JSONObject> ds1 = dataStreamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (JSONObject.isValid(value)) {
                    out.collect(JSONObject.parseObject(value));
                }
            }
        });
//        ds1.print();
        KeyedStream<JSONObject, String> keyBy = ds1.keyBy(data -> data.getJSONObject("common").getString("mid"));
        SingleOutputStreamOperator<JSONObject> process = keyBy.process(new ProcessFunction<JSONObject, JSONObject>() {
            private ValueState<String> ValueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                ValueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastValueState", String.class));
            }

            @Override
            public void processElement(JSONObject value, ProcessFunction<JSONObject, JSONObject>.Context ctx, Collector<JSONObject> out)
                    throws Exception {
                Long ts = value.getLong("ts");
                String s = DateFormatUtil.toDate(ts);
                String is_new = value.getJSONObject("common").getString("is_new");
                if (is_new == "1") {
                    String lastValue = ValueState.value();
                    if (lastValue == null) {
                        ValueState.update(s);
                    } else {
                        if (!lastValue.equals(s)) {
                            ValueState.update(s);
                            value.getJSONObject("common").put("is_new", "0");
                        }
                    }
                } else {
                    if (ValueState.value() == null) {
                        String yesterday = DateFormatUtil.toDate(ts - 1000 * 60 * 60 * 24);
                        ValueState.update(yesterday);
                    }
                }
                out.collect(value);
            }
        });
//        process.print();
        OutputTag<String> pageTag = new OutputTag<String>("page") {
        };
        OutputTag<String> displayTag = new OutputTag<String>("display") {
        };
        OutputTag<String> startTag = new OutputTag<String>("start") {
        };
        OutputTag<String> actionTag = new OutputTag<String>("action") {
        };
        OutputTag<String> errortag = new OutputTag<String>("error") {
        };
        SingleOutputStreamOperator<String> main = process.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject value, ProcessFunction<JSONObject, String>.Context ctx, Collector<String> out) throws Exception {
                String err = value.getString("err");
                if (err != null) {
                    ctx.output(errortag, value.toString());
                }
                value.remove("err");
                String start = value.getString("start");
                if (start != null) {
                    ctx.output(startTag, value.toJSONString());
                } else {
                    String common = value.getString("common");
                    String page = value.getString("page");
                    String ts = value.getString("ts");
                    JSONArray display = value.getJSONArray("displays");
                    if (display != null) {
                        for (int i = 0; i < display.size(); i++) {
                            JSONObject displayObj = display.getJSONObject(i);
                            JSONObject jsonObj = new JSONObject();
                            jsonObj.put("display", displayObj);
                            jsonObj.put("common", common);
                            jsonObj.put("page", page);
                            jsonObj.put("ts", ts);
                            ctx.output(displayTag, jsonObj.toJSONString());
                        }
                    }
                    JSONArray actions = value.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject actionobj = actions.getJSONObject(i);
                            JSONObject jsonObj = new JSONObject();
                            jsonObj.put("actions", actionobj);
                            jsonObj.put("common", common);
                            jsonObj.put("page", page);
                            jsonObj.put("ts", ts);
                            ctx.output(actionTag, jsonObj.toJSONString());
                        }
                    }
                    value.remove("displays");
                    value.remove("actions");
                    ctx.output(pageTag, value.toJSONString());
                }
            }
        });
        DataStream<String> pagedata = main.getSideOutput(pageTag);
        pagedata.print("page>>>>>>>>>>");
        DataStream<String> startdata = main.getSideOutput(startTag);
        startdata.print("start>>>>>>>>>>");
        DataStream<String> displaydata = main.getSideOutput(displayTag);
        displaydata.print("display>>>>>>>>>>");
        DataStream<String> actiondata = main.getSideOutput(actionTag);
        actiondata.print("action>>>>>>>>>>");
        DataStream<String> errordata = main.getSideOutput(errortag);
        errordata.print("error>>>>>>>>>>");
        String page_topic = "dwd_traffic_page_log";
        String start_topic = "dwd_traffic_start_log";
        String display_topic = "dwd_traffic_display_log";
        String action_topic = "dwd_traffic_action_log";
        String error_topic = "dwd_traffic_error_log";
        // pagedata.addSink(MyKafkaUtil.getFlinkKafkaProducer(page_topic));
        // startdata.addSink(MyKafkaUtil.getFlinkKafkaProducer(start_topic));
        // displaydata.addSink(MyKafkaUtil.getFlinkKafkaProducer(display_topic));
        // actiondata.addSink(MyKafkaUtil.getFlinkKafkaProducer(action_topic));
        // errordata.addSink(MyKafkaUtil.getFlinkKafkaProducer(error_topic));
        env.execute();
    }
}
